package com.sgcc.fj.pmos.common.utils;

import android.content.Context;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.widget.EditText;

import com.blankj.utilcode.util.ToastUtils;

import java.lang.ref.WeakReference;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: chichapaofan
 * @CreateDate: 2020/6/17
 * @Description:输入框过滤
 */
public class InputFilterUtils {

    /**
     * 给Edittext设置过滤
     *
     * @param editText
     * @param context
     */
    public static void setEditTextFilters(EditText editText, Context context) {
        WeakReference<Context> weak = new WeakReference<Context>(context);
        InputFilter[] fileList;
        if (editText.getFilters() != null && editText.getFilters().length > 0) {
            fileList = new InputFilter[editText.getFilters().length + 1];
            for (int i = 0; i < editText.getFilters().length; i++) {
                fileList[i] = editText.getFilters()[i];
            }
            fileList[fileList.length - 1] = setFilter(weak.get());
            editText.setFilters(fileList);

        } else {
            fileList = new InputFilter[]{setFilter(weak.get())};
            editText.setFilters(fileList);
        }
    }

    public static void setEditTextFilters2(EditText editText, Context context) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                String string = editText.getText().toString();
                for (int index = string.length() - 1; index >= 0; index--) {
                    String value = string.charAt(index) + "";
                    if (getUnicode(value).equals("\\u2d")) {
                        continue;
                    }
                    Pattern p = Pattern.compile("[0-9|a-zA-Z|\u4e00-\u9fa5|,|.|@|?|，|。|？|！|（|）|\u2013|\u002d|\uff0d|]+");
                    Matcher m = p.matcher(value);
                    if (!m.matches()) {
                        editText.setText(string.replace(value, ""));
                        try {
                            editText.setSelection(start);
                        } catch (Exception e) {
                            editText.setSelection(editText.getText().toString().length());
                        }
                        ToastUtils.showShort("不支持输入特殊字符以及表情");
                        break;
                    }
                    if (!TextUtils.isEmpty(SysUtil.checkSQL(value))) {
                        editText.setText(string.replace(value, ""));
                        try {
                            editText.setSelection(start);
                        } catch (Exception e) {
                            editText.setSelection(editText.getText().toString().length());
                        }
                        ToastUtils.showShort("输入内容违法，无法提交，请重新输入");
                        break;
                    }
                    if ((boolean) SysUtil.checkSpecial(value).get("special_is")) {
                        editText.setText(string.replace(value, ""));
                        try {
                            editText.setSelection(start);
                        } catch (Exception e) {
                            editText.setSelection(editText.getText().toString().length());
                        }
                        ToastUtils.showShort("包含特殊字符“ " + SysUtil.checkSpecial(value).get("special_str") + " ”无法提交，请重新输入");
                        break;
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    public static void setMaxFilters(EditText editText, int min, int max, boolean showMsg) {
        InputFilter[] fileList;
        if (editText.getFilters() != null && editText.getFilters().length > 0) {
            fileList = new InputFilter[editText.getFilters().length + 1];
            for (int i = 0; i < editText.getFilters().length; i++) {
                fileList[i] = editText.getFilters()[i];
            }
            fileList[fileList.length - 1] = getMaxFilter(min, max, showMsg);
            editText.setFilters(fileList);

        } else {
            fileList = new InputFilter[]{getMaxFilter(min, max, showMsg)};
            editText.setFilters(fileList);
        }
    }

    public static void setMaxPointLength(EditText editText, int max) {
        editText.setFilters(new InputFilter[]{new LengthFilter(editText, "10000000000000000", max)});
    }

    public static void setMaxLength(EditText editText, int max) {
        editText.setFilters(new InputFilter[]{new LengthFilter(editText, "1000001", max)});
    }

    public static void setMaxLength6(EditText editText, int max) {
        editText.setFilters(new InputFilter[]{new LengthFilter(editText, "1000000", max)});
    }

    public static void setMoneyLength(EditText editText, int max) {
        editText.setFilters(new InputFilter[]{new LengthFilter(editText, "1000", max)});
    }

    public static void setMoneyFilter(EditText editText, int count) {
        if (count == 0) {
            return;
        }
        MoneyInputFilter filter = new MoneyInputFilter();
        filter.setDecimalLength(count);
        InputFilter[] fileList;
        if (editText.getFilters() != null && editText.getFilters().length > 0) {
            fileList = new InputFilter[editText.getFilters().length + 1];
            for (int i = 0; i < editText.getFilters().length; i++) {
                fileList[i] = editText.getFilters()[i];
            }
            fileList[fileList.length - 1] = filter;
            editText.setFilters(fileList);

        } else {
            fileList = new InputFilter[]{filter};
            editText.setFilters(fileList);
        }
    }

    public static void setEmojiAndChinaFilter(EditText editText) {
        InputFilter[] fileList;
        if (editText.getFilters() != null && editText.getFilters().length > 0) {
            fileList = new InputFilter[editText.getFilters().length + 1];
            for (int i = 0; i < editText.getFilters().length; i++) {
                fileList[i] = editText.getFilters()[i];
            }
            fileList[fileList.length - 1] = getEmojiAndChinaFilter(editText.getContext());
            editText.setFilters(fileList);

        } else {
            fileList = new InputFilter[]{getEmojiAndChinaFilter(editText.getContext())};
            editText.setFilters(fileList);
        }
    }

    public static void setMaxFiltersWithoutToast(EditText editText, int max) {
        setMaxFilters(editText, 0, max, false);
    }

    /**
     * 设置过滤
     *
     * @param context
     * @return
     */
    public static InputFilter setFilter(Context context) {
        InputFilter emojiFilter = new InputFilter() {


            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                for (int index = start; index < end; index++) {
                    int type = Character.getType(source.charAt(index));
                    if (type == Character.SURROGATE) {
                        ToastUtils.showShort("不支持输入表情");
                        return "";
                    }
                }
                return null;
            }
        };
        return emojiFilter;
    }

    /**
     * 设置过滤
     *
     * @param context
     * @return
     */
    public static InputFilter getEmojiAndChinaFilter(Context context) {
        InputFilter emojiFilter = new InputFilter() {


            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                for (int index = start; index < end; index++) {
                    String c = source.charAt(index) + "";
                    int type = Character.getType(source.charAt(index));
                    if (type == Character.SURROGATE) {
                        return "";
                    }
                    Pattern p = Pattern.compile("[\u4e00-\u9fa5]+");
                    Matcher m = p.matcher(c);
                    if (m.matches()) {
                        return "";
                    }
                }
                return null;
            }
        };
        return emojiFilter;
    }

    /**
     * 设置昵称过滤
     *
     * @param context
     * @return
     */
    public static InputFilter setNickNameFilter(Context context) {
        InputFilter emojiFilter = new InputFilter() {


            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (TextUtils.isEmpty(source) || source.toString().length() == 0) return null;
                for (int index = start; index < end; index++) {
                    String value = source.charAt(index) + "";
                    if (getUnicode(value).equals("\\u2d")) {
                        continue;
                    }
                    Pattern p = Pattern.compile("[0-9|a-zA-Z|\u4e00-\u9fa5|,|.|@|?|，|。|？|！|（|）|\u2013|\u002d|\uff0d|]+");
                    Matcher m = p.matcher(value);
                    if (!m.matches()) {
                        ToastUtils.showShort("不支持输入特殊字符以及表情");
                        return "";
                    }
                    if (!TextUtils.isEmpty(SysUtil.checkSQL(value))) {
                        ToastUtils.showShort("输入内容违法，无法提交，请重新输入");
                        return "";
                    }
                    if ((boolean) SysUtil.checkSpecial(value).get("special_is")) {
                        ToastUtils.showShort("包含特殊字符“ " + SysUtil.checkSpecial(value).get("special_str") + " ”无法提交，请重新输入");
                        return "";
                    }
                }
                return null;
            }
        };
        return emojiFilter;
    }

    public static InputFilter getMaxFilter(int min, int max, boolean showMsg) {
        InputFilter maxf = (source, start, end, dest, dstart, dend) -> {
            try {
                String text = dest.toString().substring(0, dstart) + source.toString() + dest.toString().substring(dstart, dest.length());

                double input = Double.parseDouble(text);
                if (text.contains(".")) {
                    if (text.length() - text.indexOf(".") > 3) {
                        return "";
                    }
                }
                if (isInRange(min, max, input))
                    return null;
                else {
                    if (showMsg) ToastUtils.showShort("输入范围" + min + "至" + max);
                }
            } catch (Exception nfe) {
            }
            return "";
        };
        return maxf;
    }

    private static boolean isInRange(int a, int b, double c) {
        return b > a ? c >= a && c <= b : c >= b && c <= a;
    }

    public static String getUnicode(String source) {
        String returnUniCode = null;
        String uniCodeTemp = null;
        for (int i = 0; i < source.length(); i++) {
            uniCodeTemp = "\\u" + Integer.toHexString((int) source.charAt(i));//使用baichar类的charAt()的方法
            returnUniCode = returnUniCode == null ? uniCodeTemp : returnUniCode + uniCodeTemp;
        }
        return returnUniCode;//返回一个字du符的unicode的编码值}
    }


    /**
     * 设置过滤
     *
     * @param context
     * @return
     */
    public static InputFilter setemojiFilter(Context context) {
        InputFilter emojiFilter = new InputFilter() {


            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                for (int index = start; index < end; index++) {
                    int type = Character.getType(source.charAt(index));
                    if (type == Character.SURROGATE) {
                        ToastUtils.showShort("不支持输入表情");
                        return "";
                    }
                }
                return null;
            }
        };
        return emojiFilter;
    }

    public static void setImageFilter(EditText etName, Context mContext) {
        InputFilter[] fileList;
        if (etName.getFilters() != null && etName.getFilters().length > 0) {
            fileList = new InputFilter[etName.getFilters().length + 1];
            for (int i = 0; i < etName.getFilters().length; i++) {
                fileList[i] = etName.getFilters()[i];
            }
            fileList[fileList.length - 1] = InputFilterUtils.setemojiFilter(mContext);
            etName.setFilters(fileList);

        } else {
            fileList = new InputFilter[]{InputFilterUtils.setemojiFilter(mContext)};
            etName.setFilters(fileList);
        }
    }
}
